﻿<template>
  <div class="add-supply-purchase">
    <div class="form-container">
      <!-- 页面标题 -->
      <div class="page-title">
        <h2>{{ pageTitle }}</h2>
        <div class="mode-badge" :class="modeClass">
          {{ modeText }}
        </div>
      </div>

      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="120px"
        class="supply-form"
      >
        <!-- 货物名称 -->
        <el-form-item label="货物名称" prop="goodsName" required>
          <el-input
            v-model="formData.goodsName"
            placeholder="请输入货物名称"
            clearable
            :disabled="isViewMode"
          />
        </el-form-item>

        <!-- 类别类型 -->
        <el-form-item label="类别类型" prop="typeId" required>
          <el-select
            v-model="formData.typeId"
            placeholder="请选择类型"
            clearable
            :disabled="isViewMode"
          >
            <el-option label="车辆用品" :value="1" />
            <el-option label="办公用品" :value="2" />
            <el-option label="维修用品" :value="3" />
            <el-option label="其他" :value="4" />
          </el-select>
        </el-form-item>

        <!-- 材质 -->
        <el-form-item label="材质" prop="materialid" required>
          <el-select
            v-model="formData.materialid"
            placeholder="请选择材质"
            clearable
            :disabled="isViewMode"
          >
            <el-option 
              v-for="material in materialList" 
              :key="material.id" 
              :label="material.materialName" 
              :value="material.id" 
            />
          </el-select>
        </el-form-item>

        <!-- 规格 -->
        <el-form-item label="规格" prop="size">
          <el-input
            v-model="formData.size"
            placeholder="请输入规格"
            clearable
            :disabled="isViewMode"
          />
        </el-form-item>

        <!-- 产地 -->
        <el-form-item label="产地" required>
          <div class="origin-inputs">
            <div class="origin-select-wrapper">
              <el-select
                v-model="formData.country"
                placeholder="请选择国家"
                clearable
                filterable
                allow-create
                class="origin-select"
                popper-class="origin-dropdown"
                @change="handleCountryChange"
                :disabled="isViewMode"
              >
                <el-option 
                  v-for="country in countryOptions" 
                  :key="country.value"
                  :label="country.label" 
                  :value="country.value"
                  class="origin-option"
                >
                  <span class="option-text">{{ country.label }}</span>
                  <span class="option-flag">{{ country.flag }}</span>
                </el-option>
              </el-select>
            </div>
            <div class="origin-select-wrapper">
              <el-select
                v-model="formData.province"
                placeholder="请选择省/州"
                clearable
                class="origin-select"
                popper-class="origin-dropdown"
                @change="handleProvinceChange"
                :disabled="!formData.country || isViewMode"
              >
                <el-option 
                  v-for="province in filteredProvinceOptions" 
                  :key="province.value"
                  :label="province.label" 
                  :value="province.value"
                  class="origin-option"
                >
                  <span class="option-text">{{ province.label }}</span>
                  <span class="option-code">{{ province.code }}</span>
                </el-option>
              </el-select>
            </div>
          </div>
        </el-form-item>

        <!-- 数量 -->
        <el-form-item label="数量" prop="quantity" required>
          <el-input-number
            v-model="formData.quantity"
            :min="1"
            :max="9999"
            placeholder="请输入数值"
            class="quantity-input"
            controls-position="right"
            :disabled="isViewMode"
          />
        </el-form-item>

        <!-- 预计交付日期 -->
        <el-form-item label="预计交付日期" prop="expectedDeliveryDate" required>
          <el-date-picker
            v-model="formData.expectedDeliveryDate"
            type="date"
            placeholder="请输入期望交付日期"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            class="date-picker"
            :disabled="isViewMode"
          />
        </el-form-item>

        <!-- 用途描述 -->
        <el-form-item label="用途描述" prop="usageDescription" required>
          <el-input
            v-model="formData.usageDescription"
            type="textarea"
            :rows="4"
            placeholder="请输入用途描述"
            maxlength="500"
            show-word-limit
            :disabled="isViewMode"
          />
        </el-form-item>

        <!-- 备注 -->
        <el-form-item label="备注" prop="note">
          <el-input
            v-model="formData.note"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
            maxlength="200"
            show-word-limit
            :disabled="isViewMode"
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item class="button-group">
          <el-button type="primary" @click="handleSubmit" :loading="submitting" v-if="!isViewMode">
            {{ isEditMode ? '更新' : '提交审核' }}
          </el-button>
          <el-button @click="handleCancel">
            {{ isViewMode ? '返回' : '取消' }}
          </el-button>
          <el-button type="primary" @click="handleSaveDraft" v-if="!isEditMode && !isViewMode">
            保存草稿
          </el-button>
          <el-button type="success" @click="handleEdit" v-if="isViewMode">
            编辑
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed, watch, nextTick } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { materialApi } from '@/api'

// 路由
const router = useRouter()
const route = useRoute()

// 表单引用
const formRef = ref()
const submitting = ref(false)

// 材质列表
const materialList = ref([])

// 表单数据 - 根据API字段调整
const formData = reactive({
  id: null,
  goodsName: '',
  typeId: null,
  materialid: null,
  size: '',
  country: '',
  province: '',
  quantity: 1,
  expectedDeliveryDate: '',
  usageDescription: '',
  note: '',
  // 编辑时需要的原始字段
  createdTime: '',
  processDetailCode: '',
  approvalStatus: 0,
  approvalByName: ''
})

// 扩展国家选项
const countryOptions = [
  { label: '中国', value: 'china', flag: '🇨🇳' },
  { label: '美国', value: 'usa', flag: '🇺🇸' },
  { label: '日本', value: 'japan', flag: '🇯🇵' },
  { label: '德国', value: 'germany', flag: '🇩🇪' },
  { label: '英国', value: 'uk', flag: '🇬🇧' },
  { label: '法国', value: 'france', flag: '🇫🇷' },
  { label: '韩国', value: 'korea', flag: '🇰🇷' },
  { label: '意大利', value: 'italy', flag: '🇮🇹' },
  { label: '加拿大', value: 'canada', flag: '🇨🇦' },
  { label: '澳大利亚', value: 'australia', flag: '🇦🇺' },
  { label: '印度', value: 'india', flag: '🇮🇳' },
  { label: '巴西', value: 'brazil', flag: '🇧🇷' },
  { label: '俄罗斯', value: 'russia', flag: '🇷🇺' },
  { label: '墨西哥', value: 'mexico', flag: '🇲🇽' },
  { label: '泰国', value: 'thailand', flag: '🇹🇭' }
]

// 省份选项
const provinceOptions = [
  { label: '上海', value: 'shanghai', code: 'SH' },
  { label: '北京', value: 'beijing', code: 'BJ' },
  { label: '广东', value: 'guangdong', code: 'GD' },
  { label: '江苏', value: 'jiangsu', code: 'JS' },
  { label: '浙江', value: 'zhejiang', code: 'ZJ' },
  { label: '山东', value: 'shandong', code: 'SD' },
  { label: '四川', value: 'sichuan', code: 'SC' },
  { label: '湖北', value: 'hubei', code: 'HB' },
  { label: '湖南', value: 'hunan', code: 'HN' },
  { label: '河南', value: 'henan', code: 'HA' }
]

// 计算产地
const computedOrigin = computed(() => {
  if (formData.country && formData.province) {
    const country = countryOptions.find(c => c.value === formData.country)
    const province = provinceOptions.find(p => p.value === formData.province)
    return `${country?.label}-${province?.label}`
  }
  return ''
})

// 根据国家过滤省份选项
const filteredProvinceOptions = computed(() => {
  if (!formData.country) {
    return []
  }
  
  // 根据国家返回对应的省份
  const provinceMap = {
    'china': [
      { label: '上海', value: 'shanghai', code: 'SH' },
      { label: '北京', value: 'beijing', code: 'BJ' },
      { label: '广东', value: 'guangdong', code: 'GD' },
      { label: '江苏', value: 'jiangsu', code: 'JS' },
      { label: '浙江', value: 'zhejiang', code: 'ZJ' },
      { label: '山东', value: 'shandong', code: 'SD' },
      { label: '四川', value: 'sichuan', code: 'SC' },
      { label: '湖北', value: 'hubei', code: 'HB' },
      { label: '湖南', value: 'hunan', code: 'HN' },
      { label: '河南', value: 'henan', code: 'HA' }
    ],
    'usa': [
      { label: '加利福尼亚', value: 'california', code: 'CA' },
      { label: '纽约', value: 'newyork', code: 'NY' },
      { label: '德克萨斯', value: 'texas', code: 'TX' },
      { label: '佛罗里达', value: 'florida', code: 'FL' }
    ],
    'japan': [
      { label: '东京', value: 'tokyo', code: 'TY' },
      { label: '大阪', value: 'osaka', code: 'OS' },
      { label: '京都', value: 'kyoto', code: 'KY' }
    ]
  }
  
  return provinceMap[formData.country] || []
})

// 表单验证规则 - 修复产地验证问题
const formRules = {
  goodsName: [
    { required: true, message: '请输入货物名称', trigger: 'blur' }
  ],
  typeId: [
    { required: true, message: '请选择类别类型', trigger: 'change' }
  ],
  materialid: [
    { required: true, message: '请选择材质', trigger: 'change' }
  ],
  quantity: [
    { required: true, message: '请输入数量', trigger: 'blur' },
    { type: 'number', min: 1, message: '数量必须大于0', trigger: 'blur' }
  ],
  expectedDeliveryDate: [
    { required: true, message: '请选择预计交付日期', trigger: 'change' }
  ],
  usageDescription: [
    { required: true, message: '请输入用途描述', trigger: 'blur' }
  ]
}

// 自定义验证函数
const validateOrigin = (rule, value, callback) => {
  if (!formData.country || !formData.province) {
    callback(new Error('请选择完整的产地信息'))
  } else {
    callback()
  }
}

// 添加产地验证规则
formRules.origin = [
  { validator: validateOrigin, trigger: 'change' }
]

// 监听产地变化，触发验证
watch([() => formData.country, () => formData.province], () => {
  if (formRef.value && !isViewMode.value) {
    formRef.value.validateField('origin')
  }
})

// 处理国家变化
const handleCountryChange = () => {
  // 清空省份选择
  formData.province = ''
  // 触发产地验证
  if (formRef.value && !isViewMode.value) {
    formRef.value.validateField('origin')
  }
}

// 处理省份变化
const handleProvinceChange = () => {
  // 触发产地验证
  if (formRef.value && !isViewMode.value) {
    formRef.value.validateField('origin')
  }
}

// 获取材质列表
const fetchMaterialList = async () => {
  try {
    const response = await materialApi.getMaterials()

    if (response.code === 200) {
      materialList.value = response.data
    } else {
      throw new Error(response.message || '获取材质列表失败')
    }
  } catch (error) {
    console.error('获取材质列表出错:', error)
    // 如果API调用失败，使用模拟数据
    materialList.value = [
      { id: 1, materialName: "金属" },
      { id: 2, materialName: "橡胶" },
      { id: 3, materialName: "塑料" },
      { id: 4, materialName: "液体" },
      { id: 5, materialName: "纸质" }
    ]
    console.log('使用模拟材质数据')
  }
}

// 提交审核 - 根据API接口完善
const handleSubmit = async () => {
  try {
    // 手动验证产地
    if (!formData.country || !formData.province) {
      ElMessage.error('请选择完整的产地信息')
      return
    }

    await formRef.value.validate()
    submitting.value = true
    
    // 构建API请求数据 - 严格按照API接口要求
    const requestData = {
      id: isEditMode.value ? formData.id : 0, // 编辑模式使用实际ID，新增模式使用0
      goodsName: formData.goodsName,
      typeId: formData.typeId,
      materialid: formData.materialid,
      size: formData.size,
      origin: computedOrigin.value,
      quantity: formData.quantity,
      expectedDeliveryDate: formData.expectedDeliveryDate ? 
        new Date(formData.expectedDeliveryDate).toISOString() : 
        new Date().toISOString(),
      usageDescription: formData.usageDescription,
      note: formData.note,
      createdTime: isEditMode.value ? 
        (formData.createdTime || new Date().toISOString()) : 
        new Date().toISOString(),
      processDetailCode: isEditMode.value ? 
        (formData.processDetailCode || `SP${Date.now()}`) : 
        `SP${Date.now()}`,
      approvalStatus: isEditMode.value ? 
        (formData.approvalStatus || 0) : 
        0, // 待审批
      approvalByName: isEditMode.value ? 
        (formData.approvalByName || '') : 
        ''
    }

    console.log('提交数据:', requestData)

    // 调用API接口 - 根据模式选择不同的接口
    const response = isEditMode.value 
      ? await materialApi.updateSupplyPurchase(requestData)
      : await materialApi.addSupplyPurchase(requestData)

    console.log('API响应:', response)

    if (response.code === 200) {
      ElMessage.success(isEditMode.value ? '修改成功' : '添加成功')
      // 跳转到列表页面
      router.push('/SupplyPurchaseMange')
    } else {
      throw new Error(response.message || (isEditMode.value ? '修改失败' : '添加失败'))
    }
    
  } catch (error) {
    console.error('提交失败:', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error('提交失败，请重试')
    }
  } finally {
    submitting.value = false
  }
}

// 取消
const handleCancel = () => {
  ElMessage.info(isViewMode.value ? '返回列表' : '已取消')
  // 返回列表页面
  router.push('/SupplyPurchaseMange')
}

// 保存草稿
const handleSaveDraft = () => {
  console.log('保存草稿数据:', formData)
  ElMessage.success('草稿保存成功')
  // 这里可以调用保存草稿的API
}

// 编辑按钮 - 从查看模式切换到编辑模式
const handleEdit = () => {
  router.push({
    path: '/AddSupplyPurchaseManage',
    query: { id: formData.id, mode: 'edit' }
  })
}

// 重置表单
const resetForm = () => {
  formRef.value?.resetFields()
  Object.keys(formData).forEach(key => {
    if (key === 'quantity') {
      formData[key] = 1
    } else if (key === 'typeId' || key === 'materialid') {
      formData[key] = null
    } else {
      formData[key] = ''
    }
  })
}

// 检查模式
const isEditMode = computed(() => {
  return route.query.mode === 'edit' && route.query.id
})

const isViewMode = computed(() => {
  return route.query.mode === 'view' && route.query.id
})

// 页面标题
const pageTitle = computed(() => {
  if (isViewMode.value) return '物资采购详情'
  if (isEditMode.value) return '编辑物资采购'
  return '新增物资采购'
})

// 模式标签
const modeText = computed(() => {
  if (isViewMode.value) return '查看模式'
  if (isEditMode.value) return '编辑模式'
  return '新增模式'
})

const modeClass = computed(() => {
  if (isViewMode.value) return 'mode-view'
  if (isEditMode.value) return 'mode-edit'
  return 'mode-add'
})

// 解析产地信息 - 修复undefined问题
const parseOrigin = (origin) => {
  if (!origin) return { country: '', province: '' }
  
  console.log('解析产地:', origin)
  
  // 处理"美国-undefined"这种情况
  if (origin.includes('undefined')) {
    console.log('检测到undefined，尝试修复')
    const parts = origin.split('-')
    if (parts.length >= 1) {
      const countryLabel = parts[0]
      console.log('提取的国家标签:', countryLabel)
      
      // 查找对应的国家值
      const country = countryOptions.find(c => c.label === countryLabel)
      const countryValue = country ? country.value : ''
      
      console.log('找到的国家值:', countryValue)
      
      return { country: countryValue, province: '' }
    }
  }
  
  const parts = origin.split('-')
  if (parts.length >= 2) {
    const countryLabel = parts[0]
    const provinceLabel = parts[1]
    
    console.log('国家标签:', countryLabel, '省份标签:', provinceLabel)
    
    // 查找对应的国家值
    const country = countryOptions.find(c => c.label === countryLabel)
    const countryValue = country ? country.value : ''
    
    console.log('找到的国家值:', countryValue)
    
    // 如果省份标签不是undefined，才进行省份匹配
    if (provinceLabel && provinceLabel !== 'undefined') {
      // 查找对应的省份值
      const provinceMap = {
        'china': [
          { label: '上海', value: 'shanghai', code: 'SH' },
          { label: '北京', value: 'beijing', code: 'BJ' },
          { label: '广东', value: 'guangdong', code: 'GD' },
          { label: '江苏', value: 'jiangsu', code: 'JS' },
          { label: '浙江', value: 'zhejiang', code: 'ZJ' },
          { label: '山东', value: 'shandong', code: 'SD' },
          { label: '四川', value: 'sichuan', code: 'SC' },
          { label: '湖北', value: 'hubei', code: 'HB' },
          { label: '湖南', value: 'hunan', code: 'HN' },
          { label: '河南', value: 'henan', code: 'HA' }
        ],
        'usa': [
          { label: '加利福尼亚', value: 'california', code: 'CA' },
          { label: '纽约', value: 'newyork', code: 'NY' },
          { label: '德克萨斯', value: 'texas', code: 'TX' },
          { label: '佛罗里达', value: 'florida', code: 'FL' },
          { label: '华盛顿', value: 'washington', code: 'WA' },
          { label: '伊利诺伊', value: 'illinois', code: 'IL' },
          { label: '宾夕法尼亚', value: 'pennsylvania', code: 'PA' },
          { label: '俄亥俄', value: 'ohio', code: 'OH' },
          { label: '乔治亚', value: 'georgia', code: 'GA' },
          { label: '北卡罗来纳', value: 'northcarolina', code: 'NC' }
        ],
        'japan': [
          { label: '东京', value: 'tokyo', code: 'TY' },
          { label: '大阪', value: 'osaka', code: 'OS' },
          { label: '京都', value: 'kyoto', code: 'KY' },
          { label: '横滨', value: 'yokohama', code: 'YK' },
          { label: '名古屋', value: 'nagoya', code: 'NG' }
        ]
      }
      
      const provinces = provinceMap[countryValue] || []
      const province = provinces.find(p => p.label === provinceLabel)
      const provinceValue = province ? province.value : ''
      
      console.log('找到的省份值:', provinceValue)
      
      return { country: countryValue, province: provinceValue }
    } else {
      // 省份是undefined，只返回国家
      return { country: countryValue, province: '' }
    }
  }
  
  return { country: '', province: '' }
}

// 加载编辑数据 - 完善版本，确保所有字段都正确加载
const loadEditData = async (id) => {
  try {
    console.log('加载数据，ID:', id, '模式:', route.query.mode)
    
    // 调用获取详情的API
    const response = await materialApi.getSupplyPurchaseDetail(id)

    if (response.code === 200) {
      const data = response.data
      
      console.log('API返回的数据:', data)
      
      // 填充表单数据 - 确保所有字段都正确映射
      formData.id = data.id
      formData.goodsName = data.goodsName || ''
      formData.typeId = data.typeId || null
      formData.materialid = data.materialid || null
      formData.size = data.size || ''
      formData.quantity = data.quantity || 1
      formData.expectedDeliveryDate = data.expectedDeliveryDate ? data.expectedDeliveryDate.split('T')[0] : ''
      formData.usageDescription = data.usageDescription || ''
      formData.note = data.note || ''
      
      // 保存原始数据用于编辑时保持
      formData.createdTime = data.createdTime
      formData.processDetailCode = data.processDetailCode
      formData.approvalStatus = data.approvalStatus
      formData.approvalByName = data.approvalByName
      
      // 解析产地信息
      const originInfo = parseOrigin(data.origin)
      formData.country = originInfo.country
      formData.province = originInfo.province
      
      console.log('填充后的表单数据:', formData)
      console.log('解析后的产地信息:', originInfo)
      
      // 等待下一个tick确保DOM更新
      await nextTick()
      
      // 只在非查看模式下触发验证
      if (formRef.value && !isViewMode.value) {
        formRef.value.validateField('origin')
      }
      
      ElMessage.success('数据加载成功')
    } else {
      throw new Error(response.message || '获取详情失败')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败，请重试')
  }
}

onMounted(() => {
  console.log('物资采购页面已加载')
  
  // 加载材质列表
  fetchMaterialList()
  
  // 如果是编辑或查看模式，加载数据
  if (isEditMode.value || isViewMode.value) {
    loadEditData(route.query.id)
  }
})
</script>

<style scoped>
.add-supply-purchase {
  padding: 20px;
  background-color: #f5f5f5;
  min-height: 100vh;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.form-container {
  max-width: 800px;
  margin: 0 auto;
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.page-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 2px solid #f0f0f0;
}

.page-title h2 {
  margin: 0;
  font-size: 24px;
  font-weight: 600;
  color: #333;
}

.mode-badge {
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 14px;
  font-weight: 500;
}

.mode-view {
  background: #e6f7ff;
  color: #1890ff;
}

.mode-edit {
  background: #f6ffed;
  color: #52c41a;
}

.mode-add {
  background: #fff7e6;
  color: #fa8c16;
}

.supply-form {
  width: 100%;
}

.origin-inputs {
  display: flex;
  gap: 12px;
  width: 100%;
}

.origin-select-wrapper {
  flex: 1;
}

.origin-select {
  width: 100%;
}

.origin-option {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.option-text {
  flex: 1;
}

.option-flag, .option-code {
  font-size: 12px;
  color: #666;
  margin-left: 8px;
}

.quantity-input {
  width: 200px;
}

.date-picker {
  width: 200px;
}

.button-group {
  margin-top: 30px;
  text-align: center;
}

.button-group .el-button {
  margin: 0 8px;
}

/* 查看模式样式 */
.supply-form :deep(.el-input.is-disabled .el-input__inner),
.supply-form :deep(.el-select.is-disabled .el-input__inner),
.supply-form :deep(.el-textarea.is-disabled .el-textarea__inner) {
  background-color: #f5f5f5;
  color: #666;
  cursor: not-allowed;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .add-supply-purchase {
    padding: 10px;
  }
  
  .form-container {
    padding: 20px;
  }
  
  .page-title {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .origin-inputs {
    flex-direction: column;
    gap: 8px;
  }
  
  .quantity-input,
  .date-picker {
    width: 100%;
  }
}
</style>